package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * @Classname RefreshInterceptor
 * @Description 这个拦截器全放行，主要功能存储和刷新redis数据
 * @Date 2022/5/10 13:54
 * @Created by 86182
 */
public class RefreshInterceptor implements HandlerInterceptor {
    private Log logger = Log.get(LoginInterceptor.class);
    private StringRedisTemplate stringRedisTemplate;

    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、通过redis获取用户信息     犯错 用response获取 一直获取不到值
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //2、基于token获取redis用户信息
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().
                entries(LOGIN_USER_KEY + token);
        logger.info("登录拦截器:" + StrUtil.toString(userMap));
        //3、判断用户是否存在，如果存在放行，不存在就行拦截
        if (userMap.isEmpty()) {
            return true;
        }
        //4、存在数据存入到ThreadLocal
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //5、刷新token
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
        System.out.println("afterCompletion--------------");
    }
}
